package action

/**
 * @Description action模块
 * @Author 007lz
 * @Date 2024/7/12 下午2:56
 **/
import (
	"context"
	"errors"
	"fmt"

	"gitee.com/git-lz/twelve/model/task"
)

type newIActionFuncMap func() IAction

type IAction interface {
	OnPrepare(ctx context.Context, params *task.ExecActionParams) error
	Do(ctx context.Context) error
	OnComplete(ctx context.Context, response any) error
}

var actionMap = map[string]newIActionFuncMap{
	"HTTP": func() IAction {
		return NewHttpAction()
	},
}

func Process(ctx context.Context, params *task.ExecActionParams) error {
	action, err := getActionByType(params.ActionInfo.Type)
	if err != nil {
		return err
	}

	if err := action.OnPrepare(ctx, params); err != nil {
		return err
	}

	if err := action.Do(ctx); err != nil {
		return err
	}

	if err := action.OnComplete(ctx, nil); err != nil {
		return err
	}

	return nil
}

func getActionByType(typ string) (IAction, error) {
	actionFunc, ok := actionMap[typ]
	if !ok {
		return nil, errors.New(fmt.Sprintf("actionFuncMap type = (%v) not exits", typ))
	}

	return actionFunc(), nil
}
